package com.kehutong.house.admin;

import com.kehutong.house.entity.Supplier;
import com.kehutong.house.entity.TimeGroup;
import com.kehutong.house.util.DateUtils;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

/**
 * TODO 门禁设备时间组管理
 *
 * @author zhouweipeng
 * @version 1.0
 * @date 2021/7/29 14:32
 */
@MvcAction
@ReqMapping("/admin/basic/time/group")
public class TimeGroupController {
    @Inject
    private JdbcSession jdbcSession;

    @ReqMapping("/list")
    public Page<TimeGroup> list(JSONObject jsonObject) throws Exception {
        FindPage<TimeGroup> findPage = jdbcSession.findPage(TimeGroup.class);
        findPage.eq("deleted",false);
        String name = jsonObject.getString("name");
        if(Objects.nonEmpty(name)){
            findPage.eq("name",name);
        }
        Page<TimeGroup>page = findPage.exe();
        page.getList().forEach(item->{
            item.setBeginTimeStr(DateUtils.timestampToStr(item.getBeginTime(),DateUtils.PATTERN_3));
            item.setEndTimeStr(DateUtils.timestampToStr(item.getEndTime(),DateUtils.PATTERN_3));
        });
        return page;
    }
    @Bean(newInstance=true, copy=true)
    @ReqMapping("/save")
    public Object save(TimeGroup timeGroup)throws Exception  {
        timeGroup.setBeginTime(DateUtils.strFormatTimetamp(timeGroup.getBeginTimeStr()+" 00:00:00",DateUtils.PATTERN_1));
        timeGroup.setEndTime(DateUtils.strFormatTimetamp(timeGroup.getEndTimeStr()+" 00:00:00",DateUtils.PATTERN_1));
        jdbcSession.insert(timeGroup);
        return Result.success(timeGroup);
    }
    @Bean(newInstance=true, copy=true)
    @ReqMapping("/update")
    public Object update(TimeGroup timeGroup)throws Exception  {
        jdbcSession.updateById(timeGroup);
        return Result.success(timeGroup);
    }
    @ReqMapping("/delete")
    public Object delete(TimeGroup timeGroup) throws Exception {
        if (Objects.nonNull(timeGroup)) {
            timeGroup.setDeleted(true);
            jdbcSession.updateById(timeGroup);
        }
        return Result.success();
    }
    @ReqMapping("/get")
    public Object get(String id) throws Exception {
        TimeGroup timeGroup=jdbcSession.findById(TimeGroup.class,id);
        timeGroup.setBeginTimeStr(DateUtils.timestampToStr(timeGroup.getBeginTime(),DateUtils.PATTERN_3));
        timeGroup.setEndTimeStr(DateUtils.timestampToStr(timeGroup.getEndTime(),DateUtils.PATTERN_3));
        return timeGroup;
    }
}
